package filter

import (
	"adam2/internal/model"
	"adam2/internal/properties"
	"anubis-framework/pkg/io"
	"gorm.io/gorm"
)

// 过滤器：删除n日内上涨超过阈值的股票
type UpBeyondThresholdWithinNDateFilter struct {
	db *gorm.DB
}

// 初始化
func (u *UpBeyondThresholdWithinNDateFilter) Init(db *gorm.DB) {
	u.db = db
}

// 执行
func (u *UpBeyondThresholdWithinNDateFilter) DoFilter(transactionDate string) {
	io.Infoln("过滤器：删除n日内上涨超过阈值的股票，交易日期[%s]", transactionDate)

	var quantStockFilterArray model.QuantStockFilterArray = model.QuantStockFilterArray{}
	u.db.Raw("select * from quant_stock_filter").Scan(&quantStockFilterArray)

	for _, quantStockFilter := range quantStockFilterArray {
		// n天前的交易记录
		var nDateStockTransactionDataAll model.StockTransactionDataAll = model.StockTransactionDataAll{}
		u.db.Raw("select * from (select * from (select * from ("+
			"select * from stock_transaction_data_all t where t.code_ = ? and t.date_ <= to_date(?, 'yyyy-mm-dd') order by t.date_ desc) "+
			"where rownum <= ?) t2 order by t2.date_ asc) where rownum <= 1",
			quantStockFilter.StockCode, transactionDate, properties.QuantProperties_.BacktrackNDate).Scan(&nDateStockTransactionDataAll)

		// 当前的交易记录
		var currentStockTransactionDataAll model.StockTransactionDataAll = model.StockTransactionDataAll{}
		u.db.Raw("select * from stock_transaction_data_all t where t.code_ = ? and t.date_ = to_date(?, 'yyyy-mm-dd')",
			quantStockFilter.StockCode, transactionDate).Scan(&currentStockTransactionDataAll)

		// 删除记录
		if (currentStockTransactionDataAll.ClosePrice-nDateStockTransactionDataAll.ClosePrice)/currentStockTransactionDataAll.ClosePrice >= properties.QuantProperties_.UpThresholdLimit {
			u.db.Exec("delete from quant_stock_filter t where t.stock_code = ?", quantStockFilter.StockCode)
		}
	}
}
